package com.szy.news.activity;
/**
 * 登录实现
 * */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.renren.Renren;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.google.gson.Gson;
import com.szy.news.control.MyApplication;
import com.szy.news.util.JsonUtils;
import com.szy.news.util.ToMD5;
import com.szy.news.util.URL;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener, PlatformActionListener, Callback {
	static LoginActivity s;
	private ImageButton btn_back;
	private ImageButton btn_QQ;
	private ImageButton btn_renren;
	private ImageButton btn_sina;
	private Button tv_regist;
	private EditText et_username,et_password;
	private CheckBox autologin; 
	private Button btn_login;
	private SharedPreferences sp; 
	private ProgressDialog pd;
	private String responseMsg = "";
	private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟  
    private static final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟  
    private static final int LOGIN_OK = 1;  
    public MyApplication my;
    
    private int LOGIN_TYPE;
    private String WEIBO_NAME = "name";
    private static final int MSG_TOAST = 1;
    private static final int MSG_CANCEL_NOTIFY = 3;
    private static final int MSG_ACTION_CCALLBACK = 2;
    private ImageButton ibtn_sina;
	private ImageButton ibtn_tecent;
	private ImageButton ibtn_renren;

    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);
		sp = getSharedPreferences("userdata", 0);
		init();
		
		
//		//监听记住密码选项
//		autologin.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
//
//			@Override
//			public void onCheckedChanged(CompoundButton buttonView,
//					boolean isChecked) {
//				if (isChecked) {    
//					Editor editor = sp.edit();
//					editor.putString("username", et_username.getText()
//							.toString());
//                    editor.putString("password", et_password.getText()  
//                            .toString());  
//                    editor.commit();  
//                    et_username.setText(sp.getString("username", ""));  
//                    et_password.setText(sp.getString("password", ""));  
//                }  
//			}
//			
//		});
	}

	private void init() {
		btn_back = (ImageButton) findViewById(R.id.login_back);
		btn_back.setOnClickListener(this);
		tv_regist = (Button) findViewById(R.id.regist);
		tv_regist.setOnClickListener(this);
		et_username = (EditText) findViewById(R.id.username);
		et_username.setOnClickListener(this);
		et_password = (EditText) findViewById(R.id.password);
		et_password.setOnClickListener(this);
		btn_login = (Button) findViewById(R.id.login_btn);
		btn_login.setOnClickListener(this);
		autologin = (CheckBox) findViewById(R.id.autologin);
		//第三方授权
//		btn_QQ = (ImageButton) findViewById(R.id.imageButton_QQ);
//		btn_QQ.setOnClickListener(this);
//		btn_renren = (ImageButton) findViewById(R.id.imageButton_renren);
//		btn_renren.setOnClickListener(this);
//		btn_sina = (ImageButton) findViewById(R.id.imageButton_sina);
//		btn_sina.setOnClickListener(this);
//		
		my=(MyApplication) this.getApplication();
		
		ibtn_sina = (ImageButton) findViewById(R.id.imageButton_sina);
		ibtn_sina.setOnClickListener(this);
		ibtn_tecent = (ImageButton) findViewById(R.id.imageButton_QQ);
		ibtn_tecent.setOnClickListener(this);
		ibtn_renren = (ImageButton) findViewById(R.id.imageButton_renren);
		ibtn_renren.setOnClickListener(this);

		
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.login, menu);
//		return true;
//	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		final Intent intent;
//		Intent intent = new Intent();
		if (id == R.id.login_back) {
			LoginActivity.this.finish();
//			Intent in=new Intent(LoginActivity.this,NewsDetailsActivity.class);
//			startActivity(in);
//			intent.setClass(this, NewsDetailsActivity.class);
//			startActivity(intent);
//			finish();
		}else if (id == R.id.regist) {
			intent = new Intent(this, RegistActivity.class);
			startActivity(intent);
			my.setUsername(et_username.getText().toString().trim());
			finish();
		}else if (id == R.id.login_btn) {			
			LoginBtn();
			my.setUsername(et_username.getText().toString().trim());	
		}else if (id == R.id.imageButton_sina) {
			LOGIN_TYPE = 1;
			SinaWeibo sina = new SinaWeibo(LoginActivity.this);
			sina.SSOSetting(true);
			sina.setPlatformActionListener(LoginActivity.this);
			sina.showUser(null);
		} else if (id == R.id.imageButton_QQ) {
			LOGIN_TYPE = 2;
			TencentWeibo tencent = new TencentWeibo(LoginActivity.this);
			tencent.SSOSetting(true);
			tencent.setPlatformActionListener(LoginActivity.this);
			tencent.showUser(null);
		} else if (id == R.id.imageButton_renren) {
			LOGIN_TYPE = 3;
			Renren renren = new Renren(LoginActivity.this);
			renren.SSOSetting(true);
			renren.setPlatformActionListener(LoginActivity.this);
			renren.showUser(null);
		}

	}

	private void LoginBtn() {
		if (et_username.getText().toString().trim().equals("")
				||et_username.getText().toString().length()<4
				||et_username.getText().toString().length()>20) {
			Toast.makeText(this, "用户名介于4到20字符之间！", Toast.LENGTH_SHORT).show();
		}else if(et_password.getText().toString().trim().equals("")
				||et_password.getText().toString().length()<8
				||et_password.getText().toString().length()>16) {
			Toast.makeText(this, "密码不符合规范", Toast.LENGTH_SHORT).show();
		}else {
			//定义ProgressDialog进度条对话框
			pd = new ProgressDialog(this);
			//设置提示信息
			pd.setMessage("正在登陆，请稍后...");
			//设置不可以用返回键取消
			pd.setCancelable(true);
			//设置样式为横向
			pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			//开启进度条对话框显示
			pd.show();
			//启动新线程完成服务器操作
			new Thread(new LoginThread()).start();
		}
	}
	
	
	// LoginThread线程类  
    class LoginThread implements Runnable {  
  
        @Override  
        public void run() {  
            String username = et_username.getText().toString();  
            String password = et_password.getText().toString(); 
            
            boolean checkstatus = sp.getBoolean("checkstatus", false);  
            if (checkstatus) {  
                // 获取已经存在的用户名和密码  
                String realUsername = sp.getString("username", "");  
                String realPassword = sp.getString("password", "");  
                if ((!realUsername.equals("")) && !(realUsername == null)  
                        || (!realPassword.equals(""))  
                        || !(realPassword == null)) {  
                    if (username.equals(realUsername)  
                            && password.equals(realPassword)) {  
                        username = et_username.getText().toString();  
                        password = et_password.getText().toString(); 
//                        MyApplication ma=(MyApplication) this.getApplication();
//                        s = username;
                        
                    }  
                }  
            } else {  
                password = ToMD5.md5(password);  
            }  
  
            // URL合法，但是这一步并不验证密码是否正确  
            boolean loginValidate = loginServer(username, password);  
            Message msg = handler.obtainMessage();  
            if (loginValidate) {  
                if (responseMsg.equals("success")) {  
                    msg.what = 0;  
                    handler.sendMessage(msg);  
                }else if(responseMsg.equals("chongfu")){
                	msg.what = 3;
                	handler.sendMessage(msg);  
                } else {  
                    msg.what = 1;  
                    handler.sendMessage(msg);  
                }  
  
            } else {  
                msg.what = 2;  
                handler.sendMessage(msg);  
            }  
        }  
  
    }
    
    
 // Handler  
    Handler handler = new Handler() {  
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case 0:  
                pd.cancel();  
                Toast.makeText(getApplicationContext(), "登录成功！",  
                        300).show();  
                Bundle bundle = new Bundle();  
                bundle.putString("username", et_username.getText().toString());
//                Intent intent = new Intent();  
//              intent.setClass(LoginActivity.this, MainActivity.class);
                my.setFlag(true);
                LoginActivity.this.finish();
//                intent.setClass(LoginActivity.this, NewsDetailsActivity.class);
//                Intent in=new Intent(LoginActivity.this,MainActivity.class);
//                Toast.makeText(LoginActivity.this, ""+my.isFlag(), 1000).show();
//                startActivity(in);
//                intent.putExtras(bundle);  
//                // 返回intent  
//                setResult(RESULT_OK, intent);  
                LoginActivity.this.finish();  
  
                break;  
            case 1:  
                pd.cancel();  
                Toast.makeText(getApplicationContext(), "输入的密码错误",  
                        Toast.LENGTH_SHORT).show();  
                break;  
            case 2:  
                pd.cancel();  
                Toast.makeText(getApplicationContext(), "服务器连接失败",  
                        Toast.LENGTH_SHORT).show();  
                break;  
            case 3:  
                pd.cancel();  
                Toast.makeText(getApplicationContext(), "该用户已登录",  
                        Toast.LENGTH_SHORT).show();  
                break;  
            }  
  
        }  
    };  
    
    
    
    private boolean loginServer(String username, String password) {  
        boolean loginValidate = false;  
        // 使用apache HTTP客户端实现  
       //String urlStr = "http://192.168.137.1:8080/web/LoginServlet";
        HttpPost request = new HttpPost(URL.login_url);  
        // 如果传递参数多的话，可以丢传递的参数进行封装  
        List<NameValuePair> params = new ArrayList<NameValuePair>();  
        // 添加用户名和密码  
        params.add(new BasicNameValuePair("username", username));  
        params.add(new BasicNameValuePair("password", password));  
        try {  
            // 设置请求参数项  
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
            HttpClient client = getHttpClient();  
            // 执行请求返回相应  
            HttpResponse response = client.execute(request);  
  
            // 判断是否请求成功  
            if (response.getStatusLine().getStatusCode() == 200) {  
                loginValidate = true;  
                // 获得响应信息  
                responseMsg = EntityUtils.toString(response.getEntity());
               
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return loginValidate;  
    }  
  
    // // 初始化HttpClient，并设置超时  
    public HttpClient getHttpClient() {  
        BasicHttpParams httpParams = new BasicHttpParams();  
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
        HttpClient client = new DefaultHttpClient(httpParams);  
        return client;  
    }  
    
    @Override
	public void onCancel(Platform platform, int action) {
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 3;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}

	@Override
	public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
		JsonUtils ju = new JsonUtils();
		String json = ju.fromHashMap(res);
		Gson g = new Gson();
		
		if (LOGIN_TYPE == 1) {
			platform = ShareSDK.getPlatform(this, SinaWeibo.NAME);
		} else if (LOGIN_TYPE == 2) {
			platform = ShareSDK.getPlatform(this, TencentWeibo.NAME);
		} else if (LOGIN_TYPE == 3) {
			platform = ShareSDK.getPlatform(this, Renren.NAME);
		}
		
		try {
			JSONObject obj = new JSONObject(json);
			java.lang.System.out.println(json);
			String names = obj.getString(WEIBO_NAME);
			if (names.equals("")) {
				Toast.makeText(this, "未获取到用户名", Toast.LENGTH_SHORT).show();
			} else {
				my.setUsername(names);
				my.setFlag(true);
			}
			Log.e("name", names);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 1;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}

	@Override
	public void onError(Platform platform, int action, Throwable t) {
		t.printStackTrace();
		t.getMessage();
		
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 2;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}  
    
	@Override
	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}
	
	
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_TOAST:{
			String text = String.valueOf(msg.obj);
			Toast.makeText(LoginActivity.this, text, Toast.LENGTH_SHORT).show();
		}
		break;
		case MSG_ACTION_CCALLBACK:{
			switch (msg.arg1) {
			case 1:{//授权成功
				showNotification(2000,"Auth successfully");
				
				switch (LOGIN_TYPE) {
				case 1:
					Platform pf1 = ShareSDK.getPlatform(LoginActivity.this, SinaWeibo.NAME);
					Log.e("sharesdk use_id", pf1.getDb().getUserId()); //获取用户id
					Log.e("sharesdk use_name", pf1.getDb().getUserName());//获取用户名称
					Log.e("sharesdk use_icon", pf1.getDb().getUserIcon());//获取用户头像
					break;

				case 2:
					Platform pf2 = ShareSDK.getPlatform(LoginActivity.this, SinaWeibo.NAME);
					Log.e("sharesdk use_id", pf2.getDb().getUserId()); //获取用户id
					Log.e("sharesdk use_name", pf2.getDb().getUserName());//获取用户名称
					Log.e("sharesdk use_icon", pf2.getDb().getUserIcon());//获取用户头像
					break;
					
				case 3:
					Platform pf3 = ShareSDK.getPlatform(LoginActivity.this, SinaWeibo.NAME);
					Log.e("sharesdk use_id", pf3.getDb().getUserId()); //获取用户id
					Log.e("sharesdk use_name", pf3.getDb().getUserName());//获取用户名称
					Log.e("sharesdk use_icon", pf3.getDb().getUserIcon());//获取用户头像
					break;
				}
			}
				
			break;

			case 2: {//失败
				String expName = msg.obj.getClass().getSimpleName();
				showNotification(2000, "Auth unsuccessfully");
					
			}
			break;
			
			case 3: {//取消
				showNotification(2000, "Cancel authorization");
			} 
			break;
			
			
			}
		}
		break;

		case MSG_CANCEL_NOTIFY: {
			NotificationManager nm = (NotificationManager) msg.obj;
			if (nm != null) {
				nm.cancel(msg.arg1);
			}
		}
		break;
		}
		return false;
	}
	
	//在状态栏提示分享操作
	private void showNotification(long cancelTime, String text) {
		Context app = getApplicationContext();
		NotificationManager nm = (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE);
		final int id = Integer.MAX_VALUE/13+1;
		nm.cancel(id);
		
		long when = java.lang.System.currentTimeMillis();
		Notification notification = new Notification(R.drawable.ic_launcher, text, when);
		PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(), 0);
		notification.setLatestEventInfo(app, "sharesdk test", text, pi);
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		nm.notify(id, notification);
		
		if (cancelTime > 0) {
			Message msg = new Message();
			msg.what = MSG_CANCEL_NOTIFY;
			msg.obj = nm;
			msg.arg1 = id;
			UIHandler.sendMessageDelayed(msg, cancelTime, this);
		}
	}

	
}
